<template>
    <div  class="my-device-list">
      <MyDevice
          v-for="device in myDeviceList"
          :key="device.id"
          :init-device="device"
          init-mode="view"
          class="device-card"
          @device-dropped="handleDeviceDropped()"
          @error="handleError($event)"
      >
      </MyDevice>
      <add-device-card
        class="device-card"
        :add-device="addDevice"
        @saved="handleNewDeviceAdded()"
        @error="handleError($event)"
      >
      </add-device-card>
    </div>
</template>

<script>
import MyDevice from "@/views/new/device-management/MyDevice";
import IconFont from "@/components/new/iconfont/IconFont";
import {getUserDevices, postUserDevice} from "@/api/worker";
import AddDeviceCard from "@/components/new/device-card/AddDeviceCard";
export default {
  name: "MyDeviceList",
  components: {AddDeviceCard, IconFont, MyDevice},
  data(){
    return {
      myDeviceList: [],
      addingDevice: false,
      loadingDevice: true
    }
  },
  mounted() {
    this.loadDeviceList();
  },
  methods: {
    handleNewDeviceAdded(){
      this.loadDeviceList()
          .finally(() => {
            this.addingDevice = false;
          });
    },
    handleDeviceDropped(){
      this.loadDeviceList();
    },
    handleError(err){
      this.$message.error(err.message);
    },
    loadDeviceList() {
      return getUserDevices(sessionStorage.getItem('userid'))
        .then(res => {
          if(res.code === 200){
            this.myDeviceList = res.data;
          }else{
            throw new Error(res.msg);
          }
        })
        .catch(err => {
          this.$message.error(err.message);
        })
    },
    addDevice(device){
      return postUserDevice(sessionStorage.getItem('userid'), device)
    }
  }
}
</script>

<style scoped>
.my-device-list{
  display: grid;
  grid-template-columns: repeat(
      auto-fill,
      minmax(300px, 1fr)
    );
  grid-gap: 20px;
}
.add-btn-container{
  cursor: pointer;
  height: 260px;
  display: flex;
  justify-content: center;
}
</style>
